package cn.androidlongs.study.user.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.androidlongs.study.base.ResponeModel;
import cn.androidlongs.study.user.service.UserService;
import cn.androidlongs.study.user.vo.UserModel;
import cn.androidlongs.study.utils.CookieUtil;
import cn.androidlongs.study.utils.GsonUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<UserModel>{

    public UserModel userModel = new UserModel();
    public UserService userService;



    public void setUserService(UserService userService) {
	this.userService = userService;
    }
    public UserService getUserService() {
	return userService;
    }

    //用户的登录页面  
    public String loginPage() {
	return "loginPage";
    }

    //用户的注册页面
    public String registPage() {
	return "registPage";
    }

    public String findByName() {
	System.out.println("检查用户名");
	return NONE;
    }

    //用户的登录功能
    public String loginFunction() {

	UserModel userModel2 = getModel();
	System.out.println(" 登录 "+ userModel2.toString());
	UserModel userModel = userService.loginFunction(userModel2.getUserName(),userModel2.getPassword());
	// 获得response对象,项页面输出:
	HttpServletResponse response = ServletActionContext.getResponse();
	response.setContentType("text/html;charset=UTF-8");

	ResponeModel<String> responeModel = new ResponeModel<>();
	// 判断
	if (userModel == null) {
	    responeModel.code="1002";
	    responeModel.message = "用户密码错误或者用户不存在";
	    String json = GsonUtils.getintance().toJson(responeModel, null);
	    try {
		response.getWriter().write(json);
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    return NONE;
	} else {
	    responeModel.code="1000";
	    responeModel.message = "登录成功";
	    // 登录成功
	    // 将用户的信息存入到session中
	    ServletActionContext.getRequest().getSession()
	    .setAttribute("userModel", userModel);
	    // 页面跳转
	    String json = GsonUtils.getintance().toJson(responeModel, null);
	    try {
		response.getWriter().write(json);
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    return NONE;
	}
    }
    //用户的注册功能
    public String registFunction() {
	return "registSuccess";
    }
    @Override
    public UserModel getModel() {
	return userModel;
    }
    /**
     * 用户退出 
     * @return
     */
    public String extiLogin() {
	//销毁 session 
	ServletActionContext.getRequest().getSession().invalidate();
	return "extiLogin";
    }
}
